<?php
class Xigg_TagCloudBuilder
{
    var $_model;
    var $_cacher;

    function Xigg_TagCloudBuilder(&$model, &$cacher)
    {
        $this->_model =& $model;
        $this->_cacher =& $cacher;
    }

    function build($limit = 0, $urlScript = SABAI_URL_SCRIPT)
    {
        $id = 'Xigg_TagCloud' . $limit;
        if ($data = $this->_cacher->get($id, 'Xigg_TagCloud')) {
            $data = unserialize($data);
        } else {
            $data = $this->_getCloud($limit, $urlScript);
            $this->_cacher->save(serialize($data), $id, 'Xigg_TagCloud');
        }
        return $data;
    }

    function _getCloud($limit, $urlScript)
    {
        $tag_cloud = array();
        $tag_gw =& $this->_model->getGateway('Tag');
        if ($tags = $tag_gw->getTagsWithNodeCount($limit, 'tag_name')) {
            ksort($tags);
            require_once 'Sabai/Cloud.php';
            $cloud =& new Sabai_Cloud();
            foreach (array_keys($tags) as $i) {
                $cloud->addElement($tags[$i]['tag_name'],
                                   Sabai_URL::get('/tag/' . rawurlencode($tags[$i]['tag_name']), array(), '', $urlScript),
                                   $tags[$i]['node_count']);
            }
            $tag_cloud = $cloud->build();
        }
        return $tag_cloud;
    }
}